//
//  HomeTableViewController.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/4/26.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh
class HomeTableViewController: BaseViewTableViewController {
//    MARK:- 懒加载属性
    private lazy var titleBtn :TitleButton = TitleButton(type: .Custom)
    private lazy var popoverAnimator:PopoverAnimator = PopoverAnimator()
    private lazy var statusViewModels : [StatusViewModel] = [StatusViewModel]()
    private lazy var cellHeightCache : [String : CGFloat] = [String : CGFloat]()
    private lazy var tipLabel : UILabel = UILabel()
    private lazy var photoBrowserAnimator:PhotoBrowserAnimator = PhotoBrowserAnimator()
//    属性
    var isHaveMoreData : Bool = true
//    移除点击图片的监听
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            visitorView1.addRotationAnimate()
        }else{
//        初始化导航栏
        setupNavigationItem()
//        print(UserAccountViewModel.shareIntance.account?.access_token)
//        loadStatuses()
//        布置下拉刷新功能
        setupHeaderView()
      
//        添加提示label
        setupTipLabel()
//        setupFooterView()
//        tableView.rowHeight = UITableViewAutomaticDimension
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = 500
//        添加点击图片的监听
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.showPhotoBrowser(_:)), name: showPhotoBrowserVcNote, object: nil)
        }
        }
}
//MARK:设置UI界面
extension HomeTableViewController{
///    设置导航栏
    func setupNavigationItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftBarButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightBarButtonClick))
        titleBtn.setTitle("coderwhy", forState: .Normal)
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick), forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBtn
    }
///    设置下拉刷新
    private func setupHeaderView(){
        let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadNewData))
        headerView.setTitle("下拉刷新", forState: .Idle)
        headerView.setTitle("释放更新", forState: .Pulling)
        headerView.setTitle("加载中", forState: .Refreshing)
        tableView.mj_header = headerView
//        一开始就刷新
        headerView.beginRefreshing()
    }
///     设置上拉加载更多
//    private func setupFooterView(){
//        let footerView = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadMoreData))
//        tableView.mj_footer = footerView
//    }
///    添加提示Label
    private func setupTipLabel(){
//        设置tipLabel属性
        tipLabel.frame = CGRect(x: 0, y: 12, width: UIScreen.mainScreen().bounds.width, height: 32)
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.font = UIFont.systemFontOfSize(14)
        tipLabel.textAlignment = .Center
        tipLabel.hidden = true
//        将label添加到父控件中
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
}
//MARK:监控点击事件
extension HomeTableViewController{
    @objc func leftBarButtonClick(){
        print("点击了左边的barButton")
    }
    @objc func rightBarButtonClick(){
        print("点击了右边的barButton")
    }
    @objc func titleBtnClick(){
//        创建控制器
        let popoverVC = PopoverViewController()
//        print(popoverVC)
//        自定义样式
        popoverVC.modalPresentationStyle = .Custom
        popoverAnimator.presentFrame = CGRectMake(110, 60, 180, 250)
        popoverAnimator.animateCellBack = {
            [weak self](isPrsented:Bool) -> Void in
            self?.titleBtn.selected = isPrsented
        }
//        设置代理
        popoverVC.transitioningDelegate = popoverAnimator
//        弹出控制器
        presentViewController(popoverVC, animated: true, completion: nil)
        
    }
    @objc func showPhotoBrowser(note:NSNotification){
        guard let indexPath = note.userInfo![showPhotoBrowserVcNoteIndex] as? NSIndexPath ,picURLs = note.userInfo![showPhotoBrowserVcNotePicURLs] as? [NSURL] , objc = note.object as? PicCollectionView else{
            return
        }
        let photoBrowserVC = PhotoBrowserController(indexPath:indexPath, picURLs: picURLs)
        photoBrowserAnimator.indexPath = indexPath
        photoBrowserAnimator.presentedDelegate = objc
        photoBrowserAnimator.dismissDelegate = photoBrowserVC
        photoBrowserVC.modalPresentationStyle = .Custom
        photoBrowserVC.transitioningDelegate = photoBrowserAnimator
        presentViewController(photoBrowserVC, animated: true, completion: nil)
    }
}
// MARK:- tableView的数据源方法
extension HomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModels.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as! HomeViewCell
//        2.设置cell的数据
        cell.statusViewModel = statusViewModels[indexPath.row]
        if  indexPath.row == statusViewModels.count - 1 && isHaveMoreData {
            self.loadMoreData()
        }
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//   1.将模型取出
        let statusViewModel = statusViewModels[indexPath.row]
//        2.向缓存中，取出cell的高度
        var cellHeight = cellHeightCache["\(statusViewModel.status?.id)"]
        if cellHeight != nil {
            return cellHeight!
        }
        let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as!HomeViewCell
//        3.计算出取出模型的cell的高度
        cellHeight = cell.cellHeight(statusViewModel)
//        4.缓存cell的高度
        cellHeightCache["\(statusViewModel.status?.id)"] = cellHeight
        return cellHeight!
    }
    
}
//MARK:加载微博首页
extension HomeTableViewController{
///     下拉刷新
    @objc private func loadNewData() {
        isHaveMoreData = true
        loadStatuses(true)
    }
    /// 上拉加载更多
    @objc private func loadMoreData(){
        print("上拉加载更多")
        loadStatuses(false)
        
    }
    func loadStatuses(isNewData:Bool) {
        var since_id : Int = 0
        var max_id :Int = 0
        if statusViewModels.first?.status?.id != nil{
            since_id = isNewData ? (statusViewModels.first?.status?.id)! : 0
            max_id = isNewData ? 0 : (statusViewModels.last?.status?.id)! - 1
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let accessToken = UserAccountViewModel.shareIntance.account?.access_token else {
            return
        }
        let parameters : [String: AnyObject] = ["access_token" : accessToken,"since_id":since_id,"max_id":max_id]
        NetworkTools.shareIntance.loadStatuses(urlString:urlString, parameters:parameters) { (result, error) in
            if error != nil {
                print(error)
                self.tableView.mj_header.endRefreshing()
            }
            guard let resultArray = result else {
                print(error)
                self.tableView.mj_header.endRefreshing()
                return
            }
            var models = [StatusViewModel]()
            for resultDict in resultArray{
                let status = Status(dict: resultDict)
                models.append(StatusViewModel(status: status))
            }
            if max_id != 0 && models.count == 0{
                print("没有数据")
                self.isHaveMoreData = false
            }
            self.statusViewModels = isNewData ? models + self.statusViewModels : self.statusViewModels + models
//            只要执行reloadData()系统就会执行tavleView的两个数据源方法
//            self.tableView.reloadData()
//            缓存图片
            self.cacheImage(models)
        }
    }
//    MARK:- 下载图片
    private func cacheImage(models : [StatusViewModel]){
//        创建一个group
        let group = dispatch_group_create()
//        遍历所有的微博
        for status in models {
//            遍历所有的URL
            for url in status.picURLs{
//                将异步请求加入到group
                dispatch_group_enter(group)
               SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) in
//                将异步处理移出group
                dispatch_group_leave(group)
               })
            }
        }
//           刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            self.tableView.reloadData()
//            停止刷新
            self.tableView.mj_header.endRefreshing()
//            加载数据完毕后，停止上拉加载更多
//            self.tableView.mj_footer.endRefreshing()
//            添加提示label动画
            self.tipLabelAnmiate(models.count)
            }
        }
    private func tipLabelAnmiate(count : Int){
            tipLabel.hidden = false
            tipLabel.text = count == 0 ? "没有新微博" : "\(count)条新微博"
//            执行动画
            UIView.animateWithDuration(1.0, animations: {
                 UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: 7)!)
                self.tipLabel.frame.origin.y = 44
                }, completion: { (_) in
                    UIView.animateWithDuration(1.0, delay: 1.0, options: [], animations: {
                         UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: 7)!)
                        self.tipLabel.frame.origin.y = 12
                        }, completion: { (_) in
                            self.tipLabel.hidden = true
                    })
            })
    }
}
